package org.example.demo;

import com.mysql.cj.jdbc.Driver;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {

    public static void main(String[] args) {

        Connection connection=null;
        Statement statement =null;
        ResultSet resultSet =null;




        try {
            //1.加载数据库厂商提供的驱动,mysql的JAR包就和JAVA环境建立了关系
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.建立数据库连接
           connection = DriverManager.getConnection("");
            //3.创建Statement对象
             statement = connection.createStatement();
            //接收用户输入的姓名
            System.out.println("请输入要查询的姓名-->");
            Scanner scanner = new Scanner(System.in);
            String inputName=scanner.next();


             //4.定义SQL语句
            String sql="select id,name,age from student where name='"+inputName+"'";
            //String sql="select id,name,age from student ";
            //5.执行SQL
            resultSet = statement.executeQuery(sql);
            //6.遍历结果集，获取数据行,resultSet.next()返回一个boolean值，true表示有下一条记录
            while(resultSet.next()){
            //每进入一次循环表示读取了一行记录
                // 获取ID列的值,根据列的数据类型调用不同的方法
               long id= resultSet.getLong(1);
            //依次获取其他列的值
                String name = resultSet.getString(2);
                int age = resultSet.getInt(3);
            //打印结果
                System.out.println(MessageFormat.format("学生编号={0}，姓名={1}，年龄={2}",id,name,age));



            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {


            //依次释放资源
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }


            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
